package com.ympc.controller;

import com.ympc.mapper.CourseClassMapper;
import com.ympc.pojo.Class;
import com.ympc.pojo.Course;
import com.ympc.pojo.CourseResource;
import com.ympc.pojo.Teacher;
import com.ympc.pojo.Users;
import com.ympc.service.ClassService;
import com.ympc.service.CourseResourceService;
import com.ympc.service.CourseService;
import com.ympc.service.TeacherService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.multipart.MultipartFile;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 课程管理控制器（备授课）
 */
@Controller
@RequestMapping("/course")
public class CourseController {
    
    @Resource
    private CourseService courseService;
    
    @Resource
    private CourseResourceService courseResourceService;
    
    @Resource
    private TeacherService teacherService;
    
    @Resource
    private ClassService classService;
    
    @Resource
    private CourseClassMapper courseClassMapper;
    
    /**
     * 备授课主页 - 显示课程列表
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String courseList(HttpSession session, Model model) {
        try {
            Users user = (Users) session.getAttribute("user");
            if (user == null) {
                return "redirect:/";
            }
            
            Teacher teacher = teacherService.getTeacherByUserId(user.getId());
            if (teacher == null || teacher.getId() == null) {
                model.addAttribute("error", "请先完善教师信息");
                return "redirect:/teacher/profile";
            }
            
            // 将教师信息添加到session，以便在所有页面使用
            session.setAttribute("teacher", teacher);
            
            List<Course> courses;
            try {
                courses = courseService.getCoursesByTeacherId(teacher.getId());
                // 确保返回的不是null
                if (courses == null) {
                    courses = new java.util.ArrayList<>();
                }
            } catch (Exception e) {
                e.printStackTrace();
                courses = new java.util.ArrayList<>();
                model.addAttribute("error", "查询课程列表时出错：" + e.getMessage() + "。请检查数据库连接和course表是否存在。如果course表不存在，请先执行create_course_tables.sql脚本。");
            }
            
            model.addAttribute("courses", courses);
            model.addAttribute("teacher", teacher);
            return "course/list";
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("error", "加载课程列表时出错：" + e.getMessage());
            model.addAttribute("courses", new java.util.ArrayList<>());
            return "course/list";
        }
    }
    
    /**
     * 删除课程
     */
    @RequestMapping(value = "/delete", method = RequestMethod.GET)
    public String deleteCourse(@RequestParam Integer courseId,
                               HttpSession session,
                               RedirectAttributes redirectAttributes) {
        Users user = (Users) session.getAttribute("user");
        if (user == null) {
            return "redirect:/";
        }
        
        Teacher teacher = teacherService.getTeacherByUserId(user.getId());
        if (teacher == null || teacher.getId() == null) {
            redirectAttributes.addFlashAttribute("error", "请先完善教师信息");
            return "redirect:/teacher/profile";
        }
        
        Course course = courseService.getCourseById(courseId);
        if (course == null) {
            redirectAttributes.addFlashAttribute("error", "课程不存在");
            return "redirect:/course/list";
        }
        
        // 验证权限：只有课程所属教师可以删除
        if (!course.getTeacherId().equals(teacher.getId())) {
            redirectAttributes.addFlashAttribute("error", "无权删除此课程");
            return "redirect:/course/list";
        }
        
        try {
            // 先删除课程和班级的关联关系（避免外键约束问题）
            try {
                courseClassMapper.deleteByCourseId(courseId);
            } catch (Exception e) {
                e.printStackTrace();
                // 如果course_class表不存在或删除失败，继续执行
            }
            
            // 删除课程的所有资源文件
            try {
                List<CourseResource> resources = courseResourceService.getResourcesByCourseId(courseId);
                if (resources != null && !resources.isEmpty()) {
                    for (CourseResource resource : resources) {
                        try {
                            if (resource != null && resource.getFilePath() != null && !resource.getFilePath().isEmpty()) {
                                Path filePath = Paths.get(resource.getFilePath());
                                if (Files.exists(filePath)) {
                                    Files.delete(filePath);
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            // 继续删除其他文件，不因单个文件删除失败而中断
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                // 如果course_resource表不存在或查询失败，继续执行删除课程
            }
            
            // 删除课程（数据库外键约束会自动级联删除关联的资源记录，但我们已经手动删除了course_class关联）
            boolean success = courseService.deleteCourse(courseId);
            if (success) {
                redirectAttributes.addFlashAttribute("message", "课程删除成功");
            } else {
                redirectAttributes.addFlashAttribute("error", "课程删除失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            redirectAttributes.addFlashAttribute("error", "删除课程时出错：" + e.getMessage());
        }
        
        return "redirect:/course/list";
    }
    
    /**
     * 备授课详情页面 - 显示课程资源和结构
     */
    @RequestMapping(value = "/detail", method = RequestMethod.GET)
    public String courseDetail(@RequestParam Integer courseId, HttpSession session, Model model) {
        Users user = (Users) session.getAttribute("user");
        if (user == null) {
            return "redirect:/";
        }
        
        Course course = courseService.getCourseById(courseId);
        if (course == null) {
            model.addAttribute("error", "课程不存在");
            return "redirect:/course/list";
        }
        
        // 验证权限：只有课程所属教师可以访问
        Teacher teacher = teacherService.getTeacherByUserId(user.getId());
        if (teacher == null || !course.getTeacherId().equals(teacher.getId())) {
            model.addAttribute("error", "无权访问此课程");
            return "redirect:/course/list";
        }
        
        // 将教师信息添加到session，以便在所有页面使用
        session.setAttribute("teacher", teacher);
        
        // 获取所有资源
        List<CourseResource> allResources = courseResourceService.getResourcesByCourseId(courseId);
        
        // 按类型分组资源
        Map<String, List<CourseResource>> resourcesByType = new HashMap<>();
        resourcesByType.put("PPT", courseResourceService.getResourcesByCourseIdAndType(courseId, "PPT"));
        resourcesByType.put("源代码", courseResourceService.getResourcesByCourseIdAndType(courseId, "源代码"));
        resourcesByType.put("实践报告", courseResourceService.getResourcesByCourseIdAndType(courseId, "实践报告"));
        resourcesByType.put("软件包", courseResourceService.getResourcesByCourseIdAndType(courseId, "软件包"));
        resourcesByType.put("作业", courseResourceService.getResourcesByCourseIdAndType(courseId, "作业"));
        
        // 获取教师的所有班级，用于创建课程时选择
        List<Class> classes = classService.getClassesByTeacherId(teacher.getId());
        
        // 获取课程关联的班级ID列表
        List<Integer> associatedClassIds = courseClassMapper.findClassIdsByCourseId(courseId);
        // 获取关联的班级详细信息
        List<Class> associatedClasses = new java.util.ArrayList<>();
        if (associatedClassIds != null && !associatedClassIds.isEmpty()) {
            for (Integer classId : associatedClassIds) {
                Class clazz = classService.getClassById(classId);
                if (clazz != null) {
                    associatedClasses.add(clazz);
                }
            }
        }
        
        model.addAttribute("course", course);
        model.addAttribute("allResources", allResources);
        model.addAttribute("resourcesByType", resourcesByType);
        model.addAttribute("classes", classes);
        model.addAttribute("associatedClasses", associatedClasses);
        model.addAttribute("teacher", teacher);
        
        return "course/detail";
    }
    
    /**
     * 创建课程页面
     */
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public String createCoursePage(HttpSession session, Model model) {
        Users user = (Users) session.getAttribute("user");
        if (user == null) {
            return "redirect:/";
        }
        
        Teacher teacher = teacherService.getTeacherByUserId(user.getId());
        if (teacher == null || teacher.getId() == null) {
            model.addAttribute("error", "请先完善教师信息");
            return "redirect:/teacher/profile";
        }
        
        List<Class> classes = classService.getClassesByTeacherId(teacher.getId());
        model.addAttribute("classes", classes);
        return "course/create";
    }
    
    /**
     * 创建课程
     */
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public String createCourse(Course course, 
                                @RequestParam(value = "classIds", required = false) Integer[] classIds,
                                HttpSession session, Model model) {
        Users user = (Users) session.getAttribute("user");
        if (user == null) {
            return "redirect:/";
        }
        
        Teacher teacher = teacherService.getTeacherByUserId(user.getId());
        if (teacher == null || teacher.getId() == null) {
            model.addAttribute("error", "请先完善教师信息");
            return "redirect:/teacher/profile";
        }
        
        course.setTeacherId(teacher.getId());
        // 创建课程时不需要设置classId，因为现在使用关联表
        course.setClassId(null);
        
        boolean success = courseService.createCourse(course);
        if (success) {
            // 保存课程和班级的关联关系
            if (classIds != null && classIds.length > 0) {
                for (Integer classId : classIds) {
                    if (classId != null && classId > 0) {
                        courseClassMapper.insertCourseClass(course.getId(), classId);
                    }
                }
            }
            return "redirect:/course/detail?courseId=" + course.getId();
        } else {
            model.addAttribute("error", "创建课程失败");
            List<Class> classes = classService.getClassesByTeacherId(teacher.getId());
            model.addAttribute("classes", classes);
            return "course/create";
        }
    }
    
    /**
     * 上传课程资源（PPT等）
     */
    @RequestMapping(value = "/resource/upload", method = RequestMethod.POST)
    public String uploadResource(@RequestParam Integer courseId,
                                 @RequestParam String resourceType,
                                 @RequestParam(required = false) String resourceName,
                                 @RequestParam(required = false) Integer chapterNumber,
                                 @RequestParam(required = false) String chapterName,
                                 @RequestParam("file") MultipartFile file,
                                 HttpSession session,
                                 Model model) {
        Users user = (Users) session.getAttribute("user");
        if (user == null) {
            return "redirect:/";
        }
        
        Course course = courseService.getCourseById(courseId);
        if (course == null) {
            model.addAttribute("error", "课程不存在");
            return "redirect:/course/list";
        }
        
        // 验证权限
        Teacher teacher = teacherService.getTeacherByUserId(user.getId());
        if (teacher == null || !course.getTeacherId().equals(teacher.getId())) {
            model.addAttribute("error", "无权访问此课程");
            return "redirect:/course/list";
        }
        
        if (file == null || file.isEmpty()) {
            model.addAttribute("error", "请选择要上传的文件");
            return "redirect:/course/detail?courseId=" + courseId;
        }
        
        try {
            // 创建上传目录
            String uploadDir = "uploads/course_resources/";
            Path uploadPath = Paths.get(uploadDir);
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }
            
            // 生成文件名：课程ID_资源类型_时间戳.扩展名
            String originalFilename = file.getOriginalFilename();
            String extension = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            }
            String fileName = "course_" + courseId + "_" + resourceType + "_" + System.currentTimeMillis() + extension;
            String filePath = uploadDir + fileName;
            Path destPath = uploadPath.resolve(fileName);
            
            // 保存文件
            Files.copy(file.getInputStream(), destPath);
            
            // 创建资源记录
            CourseResource resource = new CourseResource();
            resource.setCourseId(courseId);
            resource.setResourceName(resourceName != null && !resourceName.isEmpty() ? resourceName : originalFilename);
            resource.setResourceType(resourceType);
            resource.setFilePath(filePath);
            resource.setFileName(originalFilename);
            resource.setFileSize(file.getSize());
            resource.setChapterNumber(chapterNumber);
            resource.setChapterName(chapterName);
            resource.setVisible(true);
            resource.setDownloadable(true);
            resource.setSortOrder(0);
            
            boolean success = courseResourceService.createResource(resource);
            if (success) {
                model.addAttribute("message", "资源上传成功");
            } else {
                model.addAttribute("error", "资源上传失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("error", "上传资源时出错：" + e.getMessage());
        }
        
        return "redirect:/course/detail?courseId=" + courseId;
    }
    
    /**
     * 查看资源（在线查看PPT等）
     */
    @RequestMapping(value = "/resource/view", method = RequestMethod.GET)
    public String viewResource(@RequestParam Integer resourceId,
                              @RequestParam Integer courseId,
                              HttpSession session,
                              Model model) {
        Users user = (Users) session.getAttribute("user");
        if (user == null) {
            return "redirect:/";
        }
        
        Course course = courseService.getCourseById(courseId);
        if (course == null) {
            model.addAttribute("error", "课程不存在");
            return "redirect:/course/list";
        }
        
        // 验证权限
        Teacher teacher = teacherService.getTeacherByUserId(user.getId());
        if (teacher == null || !course.getTeacherId().equals(teacher.getId())) {
            model.addAttribute("error", "无权访问此课程");
            return "redirect:/course/list";
        }
        
        CourseResource resource = courseResourceService.getResourceById(resourceId);
        if (resource == null || !resource.getVisible()) {
            model.addAttribute("error", "资源不存在或不可见");
            return "redirect:/course/detail?courseId=" + courseId;
        }
        
        // 构建文件访问URL
        String fileUrl = "/course_resources/" + resource.getFilePath().replace("uploads/course_resources/", "");
        model.addAttribute("fileUrl", fileUrl);
        model.addAttribute("resourceName", resource.getResourceName());
        model.addAttribute("courseId", courseId);
        
        return "course/viewResource";
    }
    
    /**
     * 删除资源
     */
    @RequestMapping(value = "/resource/delete", method = RequestMethod.GET)
    public String deleteResource(@RequestParam Integer resourceId,
                                 @RequestParam Integer courseId,
                                 HttpSession session,
                                 Model model) {
        Users user = (Users) session.getAttribute("user");
        if (user == null) {
            return "redirect:/";
        }
        
        Course course = courseService.getCourseById(courseId);
        if (course == null) {
            model.addAttribute("error", "课程不存在");
            return "redirect:/course/list";
        }
        
        // 验证权限
        Teacher teacher = teacherService.getTeacherByUserId(user.getId());
        if (teacher == null || !course.getTeacherId().equals(teacher.getId())) {
            model.addAttribute("error", "无权访问此课程");
            return "redirect:/course/list";
        }
        
        CourseResource resource = courseResourceService.getResourceById(resourceId);
        if (resource != null) {
            // 删除文件
            try {
                Path filePath = Paths.get(resource.getFilePath());
                if (Files.exists(filePath)) {
                    Files.delete(filePath);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            
            // 删除数据库记录
            courseResourceService.deleteResource(resourceId);
            model.addAttribute("message", "资源删除成功");
        } else {
            model.addAttribute("error", "资源不存在");
        }
        
        return "redirect:/course/detail?courseId=" + courseId;
    }
}

